package com.jump.jar.jump_jar;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.HandlerMapping;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;

@Controller
public class HelloController {
    private static Logger logger = LoggerFactory.getLogger(HelloController.class);
    private static final String API_URL = "http://auth.curcur.cn/empower.php?";
    public static Long INPUT_UID = null;

    @RequestMapping("/{value}/**")
    public void sayHello(HttpServletRequest request, HttpServletResponse response, @PathVariable("value") String value) throws IOException {
        // 获取来访Ip
        String ip = request.getRemoteAddr();
        if (sendIP(ip).equals("200")) {
//        if (true) {
            String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
            logger.info("path:" + path);
            int firstSlashIndex = path.indexOf('/');
            int secondSlashIndex = path.indexOf('/', firstSlashIndex + 1);
            INPUT_UID = Long.valueOf(path.substring(firstSlashIndex + 1, secondSlashIndex));
            logger.info("result: " + INPUT_UID);
            String finalValue = path.substring(path.indexOf(value));
            DirectLink.DOWNLOAD_ADDRESS = "https://vip.123pan.cn/" + finalValue;
            DirectLink.getSignedUrl();

            String redirectUrl = DirectLink.getSignedUrl();
            response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
            response.setHeader("Location", redirectUrl);
        } else {
            //返回未授权
            Map<String, String> responseJson = new HashMap<>();
            responseJson.put("error", "illegal_operation_your_ip_is_not_authorized");
            ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(responseJson);
            response.setContentType("application/json");
            response.getWriter().write(json);
        }

    }

    private static String sendIP(String IP) {
        try {
            URL url = new URL(API_URL + "address=" + IP);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");

            int responseCode = conn.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    ObjectMapper mapper = new ObjectMapper();
                    JsonNode jsonNode = mapper.readTree(response.toString());
                    return jsonNode.get("code").asText();
                }
            }
            conn.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
